package com.meiyuetao.myt.md.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import lab.s2jh.core.context.SpringContextHolder;
import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.security.AuthUserDetails;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.crawl.service.CrawlService;
import lab.s2jh.ctx.DynamicConfigService;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.meiyuetao.myt.core.service.SolrService;
import com.meiyuetao.myt.crawl.service.ParseCommodityService;
import com.meiyuetao.myt.kuajing.dao.KjCommodityInfoDao;
import com.meiyuetao.myt.kuajing.dao.KjSkuInfoDao;
import com.meiyuetao.myt.kuajing.entity.KjSkuInfo;
import com.meiyuetao.myt.md.dao.CommodityDao;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.entity.Commodity.CommodityStatusEnum;
import com.meiyuetao.myt.md.entity.Commodity.SolrFilterTypeEnum;
import com.meiyuetao.myt.md.entity.CommodityPic;
import com.meiyuetao.myt.md.entity.CommodityPrice;
import com.meiyuetao.myt.md.entity.CommodityVaryPrice;
import com.meiyuetao.myt.partner.dao.PartnerDao;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.purchase.dao.PurchaseOrderDetailDao;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.stock.dao.CommodityStockDao;
import com.meiyuetao.myt.vip.dao.VipCommodityDao;
import com.meiyuetao.myt.vip.dao.VipCommodityRateDao;
import com.meiyuetao.myt.vip.entity.VipCommodity;
import com.meiyuetao.myt.vip.entity.VipCommodityRate;
import com.meiyuetao.myt.vip.entity.VipLevel;
import com.meiyuetao.myt.vip.service.VipLevelService;

@Service
@Transactional
public class CommodityService extends BaseService<Commodity, Long> {
    private final Logger logger = LoggerFactory.getLogger(BaseService.class);

    @Autowired
    private KjCommodityInfoDao kjCommodityInfoDao;
    @Autowired
    private KuajingMessageService kuajingMessageService;

    @Autowired
    private KjSkuInfoDao kjSkuInfoDao;

    @Autowired
    private CommodityDao commodityDao;

    @Autowired
    private PurchaseOrderDetailDao purchaseOrderDetailDao;

    @Autowired(required = false)
    private CrawlService crawlService;

    @Autowired
    private ParseCommodityService parseCommodityService;

    @Autowired
    private CommodityVaryPriceService commodityVaryPriceService;
    @Autowired
    private VipCommodityDao vipCommodityDao;

    @Autowired
    private SolrService solrService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CommodityStockDao commodityStockDao;
    @Autowired
    private PartnerDao partnerDao;
    @Autowired
    private VipLevelService vipLevelService;
    @Autowired
    private VipCommodityRateDao vipCommodityRateDao;

    @Autowired
    DynamicConfigService dynamicConfigService;

    @Override
    protected BaseDao<Commodity, Long> getEntityDao() {
        return commodityDao;
    }

    /**
     * 同步执行URL集合数据抓取
     */
    public void startSyncCrawl(boolean importCommodity, String... urls) {
        crawlService.injectUrls(urls).startCrawlSync();
    }

    /**
     * 异步执行URL集合数据抓取
     */
    @Async
    public void startAsyncCrawl(boolean importCommodity, String... urls) {
        startSyncCrawl(importCommodity, urls);
    }

    public Commodity findByBarcode(String sku) {
        return this.findByProperty("sku", sku);
    }

    public Commodity findByErpProductId(String erpProductId, BoxOrderDetail orderDetail) {
        Commodity commodity = this.findByProperty("erpProductId", erpProductId);
        if (commodity == null) {
            commodity = new Commodity();
            commodity.setTitle(orderDetail.getBoxTitle());
            commodity.setMarketPrice(orderDetail.getPrice());
            commodity.setPrice(orderDetail.getPrice());
            commodity.setErpProductId(erpProductId);
            String sku = generateSku();
            commodity.setBarcode(sku);
            commodity.setSku(sku);
            Partner partner = getLogonPartner();
            commodity.setPartner(partner);
            this.save(commodity);
        }
        return commodity;
    }

    private Partner getLogonPartner() {
        PartnerDao partnerDao = SpringContextHolder.getBean(PartnerDao.class);
        AuthUserDetails authUserDetails = AuthContextHolder.getAuthUserDetails();
        Assert.notNull(authUserDetails);
        String aclCode = authUserDetails.getAclCode();
        if (StringUtils.isBlank(aclCode)) {
            return null;
        }
        return partnerDao.findByCode(aclCode);
    }

    public Commodity findBySku(String sku) {
        return commodityDao.findBySku(sku);
    }

    public void updatePriceByCommodityPrice(Commodity entity) {

        List<CommodityPrice> commodityPrices = entity.getCommodityPrices();
        DateTime dateTime = new DateTime();
        Boolean existNowPrice = false;
        CommodityPrice defaultCommodityPrice = null;
        // 判断是否存在当月计划价格，找到默认价格
        for (CommodityPrice cp : commodityPrices) {
            if (cp.getPriceYear().equals(dateTime.getYear()) && cp.getPriceMonth().equals(dateTime.getMonthOfYear())) {
                if (cp.getM0Price() != null) {
                    existNowPrice = true;
                    if (cp.getM0Price() != null && !cp.getM0Price().equals(entity.getPrice())) {
                        logger.debug("商品：" + entity.getTitle() + ",哎呦价：" + entity.getPrice() + ",当月计划价格：" + cp.getM0Price());
                        entity.setPrice(cp.getM0Price());
                        commodityDao.save(entity);
                    }
                }

                break;

            }
            if (cp.getDefaultPrice() != null && cp.getDefaultPrice()) {
                defaultCommodityPrice = cp;
            }
        }
        // 当月价格不存在，则取默认价格
        if (!existNowPrice && defaultCommodityPrice != null) {
            if (defaultCommodityPrice.getM0Price() != null && !defaultCommodityPrice.getM0Price().equals(entity.getPrice())) {
                logger.debug("商品：" + entity.getTitle() + ",哎呦价：" + entity.getPrice() + ",无当月计划价格，默认计划价格：" + defaultCommodityPrice.getM0Price());
                entity.setPrice(defaultCommodityPrice.getM0Price());
                commodityDao.save(entity);
            }

        }

    }

    /**
     * 查询常用商品数据用于缓存
     * 
     * @return
     */
    public Collection<Commodity> findFrequentUsedCommodities() {
        return commodityStockDao.findSalableCommodities();
    }

    public Commodity clone(Commodity commodity, String title, Boolean isCopyPic, Boolean isCopyPrice) {

        Commodity newCommodity = new Commodity();
        Field field[] = newCommodity.getClass().getDeclaredFields();
        List<String> properties = new ArrayList<String>();
        for (Field f : field) {
            String typeName = f.getGenericType().toString();
            // 集合类型属性
            if (typeName.indexOf("java.util") > -1) {
                properties.add(f.getName());
            }
        }
        String[] classProperties = new String[] { "barcode", "title", "id", "createdBy", "createdDt", "updatedBy", "updatedDt", "version", "smallPic", "circle",
                "commodityVaryPrice", "vipCommodity" };
        for (String classProperty : classProperties) {
            properties.add(classProperty);
        }
        String s = StringUtils.join(properties, ",");
        String[] removeProperties = s.split(",");

        BeanUtils.copyProperties(commodity, newCommodity, removeProperties);

        String sku = RandomStringUtils.randomNumeric(8);
        while (commodityDao.findBySku(sku) != null) {
            sku = RandomStringUtils.randomNumeric(8);
        }
        newCommodity.setSku(sku);
        newCommodity.setTitle(title);
        if (isCopyPic) {
            newCommodity.setSmallPic(commodity.getSmallPic());
            List<CommodityPic> commodityPicList = new ArrayList<CommodityPic>();
            for (CommodityPic commodityPic : commodity.getCommodityPics()) {
                CommodityPic newCommodityPic = new CommodityPic();
                BeanUtils.copyProperties(commodityPic, newCommodityPic, new String[] { "id", "createdBy", "createdDt", "updatedBy", "updatedDt", "version", "commodity" });
                newCommodityPic.setCommodity(newCommodity);
                commodityPicList.add(newCommodityPic);
            }
            newCommodity.setCommodityPics(commodityPicList);
        }
        newCommodity = commodityDao.save(newCommodity);
        if (isCopyPrice) {
            List<CommodityPrice> commodityPriceList = newCommodity.getCommodityPrices();
            for (CommodityPrice commodityPic : commodity.getCommodityPrices()) {
                CommodityPrice newCommodityPrice = new CommodityPrice();
                BeanUtils.copyProperties(commodityPic, newCommodityPrice, new String[] { "id", "createdBy", "createdDt", "updatedBy", "updatedDt", "version", "commodity" });
                newCommodityPrice.setCommodity(newCommodity);
                commodityPriceList.add(newCommodityPrice);
            }
            newCommodity.setCommodityPrices(commodityPriceList);
            newCommodity.setCircle(commodity.getCircle());
            CommodityVaryPrice commodityVaryPrice = commodityVaryPriceService.findOne(commodity.getId());
            CommodityVaryPrice newCommodityVaryPrice = new CommodityVaryPrice();
            BeanUtils.copyProperties(commodityVaryPrice, newCommodityVaryPrice, new String[] { "id", "createdBy", "createdDt", "updatedBy", "updatedDt", "version", "commodity" });
            newCommodityVaryPrice.setCommodity(newCommodity);
            newCommodity.setCommodityVaryPrice(newCommodityVaryPrice);
            commodityVaryPriceService.save(newCommodityVaryPrice);
        }
        // vipCommodity.copy
        VipCommodity vipCommodity = vipCommodityDao.findOne(commodity.getId());
        VipCommodity newVipCommodity = new VipCommodity();
        BeanUtils.copyProperties(vipCommodity, newVipCommodity, new String[] { "id", "createdBy", "createdDt", "updatedBy", "updatedDt", "version", "commodity", "commoditySid" });
        newVipCommodity.setCommodity(newCommodity);
        newVipCommodity.setCommoditySid(newCommodity.getId());
        newVipCommodity.setEnable(false);
        vipCommodityDao.save(newVipCommodity);
        List<VipCommodityRate> vipCommodityRates = commodity.getVipCommodityRates();
        for (VipCommodityRate vipCommodityRate : vipCommodityRates) {
            VipCommodityRate vcr = new VipCommodityRate();
            vcr.setCommodity(newCommodity);
            vcr.setVipLevel(vipCommodityRate.getVipLevel());
            vcr.setLevelRate(vipCommodityRate.getLevelRate());
            vipCommodityRateDao.save(vcr);
        }
        newCommodity.setVipCommodity(newVipCommodity);
        newCommodity = this.save(newCommodity);
        return newCommodity;
    }

    @Override
    public Commodity save(Commodity entity) {
        if (entity.getKjCommodityInfo() != null) {
            entity.getKjCommodityInfo().setCommodity(entity);
            kjCommodityInfoDao.save(entity.getKjCommodityInfo());
        }
        super.save(entity);
        if (entity.getCommodityVaryPrice() == null) {
            CommodityVaryPrice commodityVaryPrice = new CommodityVaryPrice();
            commodityVaryPrice.setCommodity(entity);
            commodityVaryPriceService.save(commodityVaryPrice);
        }
        if (entity.getVipCommodity() == null) {
            VipCommodity vipCommodity = new VipCommodity();
            vipCommodity.setCommodity(entity);
            vipCommodity.setBackMoney(BigDecimal.ZERO);
            vipCommodity.setScore(BigDecimal.ZERO);
            vipCommodity.setCommoditySid(entity.getId());
            vipCommodity.setEnable(false);
            // 需求 #6564 put forward by evan add by harvey 2015/4/23 2015/5/5
            // evan 修改回来
            // 默认返利总金额为商品价格的10%
            // vipCommodity.setBackMoney(BigDecimal.valueOf(0.1).multiply(entity.getPrice()));
            // 默认积分金额为商品价格取整
            // vipCommodity.setScore(entity.getPrice().setScale(0,
            // BigDecimal.ROUND_DOWN));
            vipCommodityDao.save(vipCommodity);
            List<VipLevel> vipLevels = vipLevelService.findAllCached();
            for (VipLevel vipLevel : vipLevels) {
                if ("MYT".equals(vipLevel.getCode()) || "PT".equals(vipLevel.getCode())) {
                    continue;
                }
                VipCommodityRate vcr = new VipCommodityRate();
                vcr.setCommodity(entity);
                vcr.setVipLevel(vipLevel);
                vcr.setLevelRate(vipLevel.getBackMoneyRate() == null ? 0 : vipLevel.getBackMoneyRate().intValue());
                vipCommodityRateDao.save(vcr);
            }
        }

        solrService.commodityIndexAsync();
        return entity;
    }

    public void putOnAndRec(Commodity commodity, boolean rec) {
        commodity.setCommodityStatus(CommodityStatusEnum.S30ONSALE);
        if (rec) {
            jdbcTemplate.execute("update iyb_recommend_commodity set is_enable = 1 where commodity_sid=" + commodity.getId());
        }
        commodityDao.save(commodity);
        // 异步更新Solr索引
        solrService.commodityIndexAsync();

    }

    public void putOff(Commodity commodity) {
        commodity.setCommodityStatus(CommodityStatusEnum.S40OFFSALE);
        commodityDao.save(commodity);
        jdbcTemplate.execute("update iyb_recommend_commodity set is_enable = 0 where commodity_sid=" + commodity.getId());
        // 异步更新Solr索引
        solrService.commodityIndexAsync();
    }

    /**
     * 获取包含敏感信息的商品列表 cfg.commodity.sensitive.info
     * 
     * @return
     */
    public List<Commodity> findContainSensitiveCommodityList() {
        List<Commodity> result = new ArrayList<Commodity>();
        /*
         * 获取系统配置中的敏感信息 将其转换为数组
         */
        String sensitiveInfos = dynamicConfigService.getString("cfg.commodity.sensitive.info");
        String[] sensitiveInfoArray;
        if (StringUtils.isNotBlank(sensitiveInfos)) {
            sensitiveInfoArray = sensitiveInfos.split(",");
        } else {
            return result;
        }
        /*
         * 遍历找包含敏感信息的商品记录
         */
        Iterable<Commodity> commodities = commodityDao.findAll();
        for (Commodity commodity : commodities) {
            String specification = commodity.getSpecification();
            if (StringUtils.isBlank(specification))
                continue;// 为空跳过，继续下一条
            for (String sensitiveInfo : sensitiveInfoArray) {
                if (specification.contains(sensitiveInfo)) {
                    result.add(commodity);
                    break;// 匹配到一个敏感词就跳出循环，不再匹配后续的词
                }
            }
        }
        return result;
    }

    public int findContainSensitiveCommodityCount() {
        return findContainSensitiveCommodityList().size();
    }

    /**
     * 导入ERP货品和美月淘后台商品的对应关系（excel）
     * 
     * @param excel
     *            Excel文件
     * @return Message
     */
    public String importErpProduct(File excel) {
        int count = 0;
        List<Row> rows;
        try {
            rows = readXls(excel);
            for (Row row : rows) {
                Cell skuCell = row.getCell(0);
                if (skuCell != null) {
                    Commodity commodity = commodityDao.findBySku(getValue(skuCell));
                    if (commodity != null) {
                        Cell erpCell = row.getCell(1);
                        commodity.setErpProductId(erpCell == null ? null : getValue(erpCell));
                        this.save(commodity);
                        count++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "加载Excel文件失败（" + e.getMessage() + ")";
        }

        return "成功导入数据" + count + "条";
    }

    // erp商品同步到数据库
    public String erpCommodityUpdate(File excel, String updateType, String solrFilterType) throws InvalidFormatException, IOException {
        List<Row> rows = readXls(excel);
        String failErpIds = "";
        int failCount = 0;
        if ("COMMODITY_UPDATE".equals(updateType)) {
            int i = 1;
            for (Row row : rows) {
                String erpId = row.getCell(0) == null ? null : getValue(row.getCell(0));
                if (erpId != null) {
                    try {
                        Commodity commodity = getCommodityForErp(erpId, solrFilterType);
                        if (commodity != null) {
                            String title = row.getCell(1) == null ? null : getValue(row.getCell(1));
                            String erpSpec = row.getCell(2) == null ? null : getValue(row.getCell(2));
                            String price = row.getCell(3) == null ? null : getValue(row.getCell(3));
                            commodity.setErpSpec(erpSpec);
                            commodity.setPrice(new BigDecimal(StringUtils.isNotBlank(price) ? price : "0.00"));
                            commodity.setMarketPrice(commodity.getPrice().multiply(new BigDecimal(1.3)).setScale(0, BigDecimal.ROUND_HALF_DOWN));
                            commodity.setSolrFilterType(SolrFilterTypeEnum.valueOf(solrFilterType));
                            if (StringUtils.isNotBlank(title)) {
                                commodity.setTitle(title);
                                this.save(commodity);
                            } else {
                                failErpIds += "erp商品Id：" + erpId + "标题为空;\r\n";
                                failCount++;
                            }
                        } else {
                            failErpIds += "erp商品Id：" + erpId + "不存在;\r\n";
                            failCount++;
                        }
                    } catch (Exception e) {
                        failErpIds += "erp商品Id：" + erpId + "失败," + e.getMessage() + ";\r\n";
                        failCount++;
                    }
                } else {
                    failErpIds += "第" + i + "行erp商品id是空;\r\n";
                    failCount++;
                }
                i++;
            }

        } else if ("COMMODITY_NEW".equals(updateType)) {
            int i = 1;
            for (Row row : rows) {
                String erpId = row.getCell(0) == null ? null : getValue(row.getCell(0));
                if (erpId != null) {
                    try {
                        Commodity commodity = getCommodityForErp(erpId, solrFilterType);
                        if (commodity == null) {
                            commodity = new Commodity();
                            String title = row.getCell(1) == null ? null : getValue(row.getCell(1));
                            String erpSpec = row.getCell(2) == null ? null : getValue(row.getCell(2));
                            String price = row.getCell(3) == null ? null : getValue(row.getCell(3));
                            commodity.setErpSpec(erpSpec);
                            commodity.setPrice(new BigDecimal(StringUtils.isNotBlank(price) ? price : "0.00"));
                            commodity.setMarketPrice(commodity.getPrice().multiply(new BigDecimal(1.3)).setScale(0, BigDecimal.ROUND_HALF_DOWN));
                            Partner partner = partnerDao.findByCode(Partner.MYT_CODE);
                            commodity.setPartner(partner);
                            commodity.setTitle(title);
                            commodity.setSku(generateSku());
                            commodity.setErpProductId(erpId);
                            commodity.setCommodityStatus(CommodityStatusEnum.S40OFFSALE);
                            commodity.setSolrFilterType(SolrFilterTypeEnum.valueOf(solrFilterType));
                            this.save(commodity);
                        } else {
                            failErpIds += "erp商品Id：" + erpId + "已经存在;\r\n";
                            failCount++;
                        }
                    } catch (Exception e) {
                        failErpIds += "erp商品Id：" + erpId + "失败," + e.getMessage() + ";\r\n";
                        failCount++;
                    }
                } else {
                    failErpIds += "第" + i + "行erp商品id是空;\r\n";
                    failCount++;
                }
                i++;
            }
        } else if ("COMMODITY_UPDATE_BY_TITLE".equals(updateType)) {
            for (Row row : rows) {
                String erpId = row.getCell(0) == null ? null : getValue(row.getCell(0));
                Commodity commodity = getCommodityForErp(erpId, solrFilterType);
                if (commodity == null) {
                    String title = getValue(row.getCell(1));
                    commodity = commodityDao.findByTitle(title);
                    if (commodity != null) {
                        commodity.setErpProductId(erpId);
                        commodity.setSolrFilterType(SolrFilterTypeEnum.valueOf(solrFilterType));
                        this.save(commodity);
                    }

                }
            }
        } else if ("UPDATE_PRICE".equals(updateType)) {
            for (Row row : rows) {
                String erpId = row.getCell(0) == null ? null : getValue(row.getCell(0));
                if (erpId != null) {
                    Commodity commodity = getCommodityForErp(erpId, solrFilterType);
                    if (commodity != null) {
                        String price = getValue(row.getCell(1));
                        if (StringUtils.isNotBlank(price)) {
                            BigDecimal costPrice = new BigDecimal(price);
                            if (costPrice.compareTo(BigDecimal.ZERO) == 1) {
                                commodity.setCostPrice(costPrice);
                                commodity.setSolrFilterType(SolrFilterTypeEnum.valueOf(solrFilterType));
                                commodityDao.save(commodity);
                            }
                        }

                    }

                }

            }

        }
        if (StringUtils.isNotBlank(failErpIds)) {
            return "失败条数：" + failCount + "\r\n" + failErpIds;
        }
        return "";
    }

    /**
     * 读取xls文件内容
     * 
     * @param excel
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    private List<Row> readXls(File excel) throws IOException, InvalidFormatException {
        InputStream is = new FileInputStream(excel);
        Workbook workbook = WorkbookFactory.create(is);
        // Map<String, String> data = new HashMap<String, String>();
        // 循环工作表Sheet
        List<Row> rows = new ArrayList<Row>();
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
            Sheet sheet = workbook.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row != null) {
                    rows.add(row);
                }
            }
        }
        return rows;
    }

    /**
     * 得到Excel表中的值
     * 
     * @param cell
     * @return
     */
    @SuppressWarnings("static-access")
    private String getValue(Cell cell) {
        if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            // return String.format("%.0f", cell.getNumericCellValue());
            return String.valueOf(cell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(cell.getStringCellValue());
        }
    }

    public String generateSku() {
        String sku = RandomStringUtils.randomNumeric(8);
        while (commodityDao.findBySku(sku) != null) {
            sku = RandomStringUtils.randomNumeric(8);
        }
        return sku;
    }

    public void saveThisAndInfo(Commodity bindingEntity, KjSkuInfo kjSkuInfo) {

        this.save(bindingEntity);
        kjSkuInfoDao.save(kjSkuInfo);
    }

    private Commodity getCommodityForErp(String erpId, String solrFilterType) {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "erpProductId", erpId),
                new PropertyFilter(MatchType.EQ, "solrFilterType", SolrFilterTypeEnum.valueOf(solrFilterType)));
        List<Commodity> commodities = this.findByFilters(groupPropertyFilter);
        if (commodities.size() != 0) {
            return commodities.get(0);
        }
        return null;
    }
}